<?php
namespace Weiping\Controller;
use Weixin\Api\WebpageApi;
use Think\Controller;

/**
 * 基础类，用于判定用户是否登录
 * @author wf
 *
 */
class BaseController extends Controller {
	protected function _initialize(){
	if(!session('?user')){
		$code = $this->_checkAuthorize();

		$settings = F('settings') ? F('settings') : M('Settings')->getField('name,value');
		C('settings', $settings);

		/* 请求网页授权令牌 */
		$api = new WebpageApi();
		$access_token = $api->getWebpageAccessToken($code);
		C('interview.access_token', $access_token);

		/* 拉取当前答题用户信息 */
		$userInfo = $api->pullUserinfo(session('openid'), $access_token);
		session('user', $userInfo);
		}
	}
	
	/**
	 * 检查是否获得客户的网页授权(该问卷系统默认采用snsapi_userinfo的scope授权)
	 * @return string  成功则返回临时授权码，失败则进入TP异常
	 */
	private function _checkAuthorize()
	{
		$code = I('get.code');

		if( empty($code) ){
			$sep = DIRECTORY_SEPARATOR;
    		
		 /* 计算问卷链接地址 */
            $host = C('settings.weixin_domain');
            $appID = C('settings.weixin_AppID');
            $redirectURL = "http://weshuoke.com/index.php/Shuoke/Index/".ACTION_NAME;
            $redirectURL = urlencode($redirectURL);
            $link = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appID}&redirect_uri={$redirectURL}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
    		
            $this->redirect($link);
		}else{
			C('interview.code', $code); //记录临时授权码
			C('interview.state', I('get.state'));
			return $code;
		}
	}
}